<?php

namespace qore_base\cli;
use \qore\base\Application;
use \qore\cli\CliControllerDispatcher;
use \Qore;

/**
 * @author Samuel Nogueira <samuel.nogueira.dev@gmail.com>
 */
class CliApplication extends Application {
	protected $_arguments;

	public function init() {
		$argv = Qore::vget($_SERVER, 'argv', array());
		$this->_arguments = $this->_parseArgs($argv);
	}
	
	public function getDispatcher() {
		return CliControllerDispatcher::i();
	}
	
	public function run() {
		echo $this->getDispatcher()->dispatch();
	}
	
	/**
	 * Returns a value only if a text arg exists, $defaultValue otherwise
	 * @return string
	 */
	public function getArgument($key, $defaultValue = null) {
		$value = Qore::vget($this->_arguments, $key, $defaultValue);
		return is_string($value) ? $value : $defaultValue;
	}
	
	/**
	 * Returns a value only if a flag exists, $defaultValue otherwise
	 * @return bool
	 */
	public function getFlag($flag, $defaultValue = false) {
		$value = Qore::vget($this->_arguments, $flag, $defaultValue);
		return is_bool($value) ? $value : $defaultValue;
	}
	
	protected static function _parseArgs($argv) {
		$args = array();
		for ($i=count($argv)-1; $i>=1; $i--) {
			$arg = $argv[$i];
			$nextArg = Qore::vget($argv, $i+1);
			
			// --key=value or --flag syntax
			if (preg_match('/^--(?P<key>[^=]+)(=(?P<value>.+))?$/', $arg, $matches)) {
				$args[$matches['key']] = isset($matches['value']) ? $matches['value'] : true;
			}
			// -abc syntax
			elseif (preg_match('/^-[a-zA-Z]+$/', $arg)) {
				$chars = str_split(substr($arg, 1));
				foreach ($chars as $key) {
					$args[$key] = true;
				}
			}
			// array[]=value syntax
			elseif (preg_match('/^(?P<key>.+)\[(?P<subkey>[^\]]*)\]=(?P<value>.+)$/', $arg, $matches)) {
				if ($matches['subkey']) {
					$args[$matches['key']][$matches['subkey']] = $matches['value'];
				} else {
					$args[$matches['key']][] = $matches['value'];
				}	
			}
			// normal syntax
			else {
				$args[] = $arg;
			}
		}
		return $args;
	}
}
